import React, { useEffect, useState } from 'react';
import { useHistory } from "react-router-dom";
import {
    Tabs, Toast, Flex, Card, Button, Badge, DatePicker, List,Modal
} from 'antd-mobile';
import { dateFormat } from "../../../model/code";
import http from "../../../model/http";  
import Header from "../../../components/header/Header";
import './standard.less'
import status1 from '../../../libs/img/user/historyStatus1.png'
import status2 from '../../../libs/img/user/historyStatus2.png'
import status3 from '../../../libs/img/user/historyStatus3.png'
import man from '../../../libs/img/user/man.png';
import woman from '../../../libs/img/user/woman.png'; 
import '../../../libs/font/iconfont.css';
// import Vconsole from 'vconsole'
// const vConsole = new Vconsole()
/**
 * @name 判断iOS
 */
const isiOS = () => {
    let u = navigator.userAgent;
    let iOs = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端\
    return iOs;
}

// let myFlg = localStorage.getItem('timeSearch') ? JSON.parse(localStorage.getItem('timeSearch')) : []

// let myDate1 = myFlg.length > 0 ? new Date(  JSON.parse(localStorage.getItem('timeSearch'))[0].slice(0,10)    ) : new Date()
// let myDate2 = myFlg.length > 0 ? new Date(  JSON.parse(localStorage.getItem('timeSearch'))[1].slice(0,10)    ) : new Date()

function ReturnVisit() {
    
    const history = useHistory();

    const [tabsData, setTabsData] = useState([])
    const [customerCrmId, setCustomerCrmId] = useState('')
    const [customerName, setCustomerName] = useState('')
    const [visitList, setVisitList] = useState([])
    const [isiOSBool, setIsiOSBool] = useState(false)

    // 外面的tabs点击
    const [tabsVal, setTabsVal] = useState('0')
    
    const nowTimeStamp= new Date()


    const [date, setDate] = useState(nowTimeStamp);
    const [date2, setDate2] = useState(nowTimeStamp)
    // 未回访数据
    const [noReturnVisitData,setNoReturnVisitData] = useState([])
    // 已回访数据
    const [returnVisit, setReturnVisit] = useState([])
    // 数据  
    const [smallTabsData, setSmallTabsData] = useState([])

    const [smalltabs, setSmalltabs] = useState([])

    const [smallTabsValue, setSmallTabsValue] = useState(0) 

    let myFlg = localStorage.getItem('timeSearch') ? JSON.parse(localStorage.getItem('timeSearch')) : []
    let [myDate1,setMyDate1]= useState( myFlg.length > 0 ? new Date(  JSON.parse(localStorage.getItem('timeSearch'))[0].slice(0,10)    ) : new Date())
    let [myDate2,setMyDate2]= useState( myFlg.length > 0 ? new Date(  JSON.parse(localStorage.getItem('timeSearch'))[1].slice(0,10)    ) : new Date())
    
    // const tabs = [
    //     { title: '1', value: 'DE0011' },
    //     { title: '2', value: 'DE0012' },
    //     { title: '3', value: 'DE0013' },
    //     { title: '4', value: 'DE0014' },
    //     { title: '5', value: 'DE0045' },
    // ];
    const [tabs, setTabs] = useState([
        { title: <Badge text={''} overflowCount={99}>未回访</Badge>, value: '0' },
        { title: <Badge text={''} overflowCount={99}>已回访</Badge>, value: '1' },
    ])
     
  
    /*渲染完成*/
    useEffect(async () => {
        // getFeedback (data.data[0].customerCrmId) 
        

      

        // if(history.location.state){
             
          
             
        //     setTimeout(() => {
        //         listFunc(0, '1')
        //     }, 200);

        // }
        
        // else{
            listFunc(0, '1')
        // }


        if(isiOS() == true){
            setIsiOSBool(true)
        }

       
    }, [])

     

    // // 点击tabs
    const tabsClick = (v,index) => {
        console.log(v.value)
        setSmallTabsValue(Number(index))
        if(tabsVal === '0'){ 
            if(noReturnVisitData.length < 1){
                return false
            }  
            let newData2 = noReturnVisitData  
            let clickData = newData2.find(elem => {
                return elem.scout_theme == v.value
            }) 
            console.log(clickData)
            
            setSmallTabsData([...clickData.data]) 

        }else{ 
            if(returnVisit.length < 1){
                return false
            }  
            let newData2 = returnVisit  
            let clickData = newData2.find(elem => {
                return elem.scout_theme == v.value
            }) 
            setSmallTabsData([...clickData.data]) 
        }
        
    }

    // 新增
    const nextStep = (e,value) => {
        e.stopPropagation();
        console.log('111')
        if(tabsVal == 0){
            // 跳计划回访
            history.push(`/clientReview/add`, {
                customerName: value.name,
                customerCrmId: value.client_id,
                originId:2,
                tb_feedback_id:value.tb_feedback_id,
                item:JSON.stringify(value)
                // srid: smallTabsValue
            })
        }
    }

    // 查询
    const submitSearch = () => {
        console.log('触发')
        listFunc(tabsVal)
    }
    // 最外层的tabs
    const bigTabsChange = (value,index) => {
        setSmallTabsData([])
        setSmalltabs([])

        setTabsVal(value) 
        // listFunc(value)
        setSmallTabsValue(0) 
        if(value === '0'){ 
            if(noReturnVisitData.length < 1){
                return false
            }
            let newData2 = noReturnVisitData 
            let filterData = newData2.map(item => {
                return {
                    title: item.scout_theme,
                    value: item.scout_theme,
                    data: item.data
                }
            })
            console.log('000:',filterData)
            if(filterData.length>0){
                setSmallTabsData([...filterData[0].data])
            }else{
                setSmallTabsData([])
            }
            setSmalltabs(filterData) 
        }else{ 

            if(returnVisit.length < 1){
                return false
            } 
            let newData2 = returnVisit
            let filterData = newData2.map(item => {
                return {
                    title: item.scout_theme,
                    value: item.scout_theme,
                    data: item.data
                }
            })
            console.log('111:',filterData)
            if(filterData.length>0){
                setSmallTabsData([...filterData[0].data])
            }else{
                setSmallTabsData([])
            }
            setSmalltabs(filterData) 
        }
    }
    // 请求
    const listFunc = async(type, beg = '2') => {
        let timeDate={}

        console.log("loaction",history.location)
        // if(history.location.state){
          
            timeDate = {
                // type: type,
                begintime: dateFormat(myDate1,'yyyy-MM-dd'),
                endtime: dateFormat(myDate2,'yyyy-MM-dd')
            }
            

         
            console.log("timeSearch",timeDate)

           
        // }else{
        //     timeDate = {
        //         // type: type,
        //         begintime: dateFormat(date,'yyyy-MM-dd'),
        //         endtime: dateFormat(date2,'yyyy-MM-dd')
        //     }
        // }
        
        const result = await http.post('/feedback/workbenchFeedbackCustomerData',timeDate)
        if(result.code == 0){
            
            // let newData = result.data 
            // let strArr1 = newData.find(elemt => {
            //     return elemt.type === 0
            // })
            // let strArr2 = newData.find(elemt => {
            //     return elemt.type === 1
            // }) 
            let strArr1 = result.data0
            let strArr2 = result.data1
            setNoReturnVisitData(strArr1)
            setReturnVisit(strArr2)

            console.log("strArr1",strArr1)
            console.log("strArr2",strArr2)


            let counts1 = 0
            let counts2 = 0
            strArr1.map(item =>{
                counts1+=item.counts
            }) 
            strArr2.map(item =>{
                counts2+=item.counts
            })
            
            // if(beg == '1'){ 
                // 底下小tabs内容
                let newData2 = (tabsVal === '0' ? strArr1 : strArr2)
                
                let filterData = newData2.map(item => {
                    return {
                        title: item.scout_theme,
                        value: item.scout_theme,
                        data: item.data
                    }
                })
             
                console.log(filterData)
                // 小tabs 的标签数据 
                if(filterData.length>0){
                    setSmallTabsData([...filterData[0].data])
                }else{
                    setSmallTabsData([])
                }
               
                setSmalltabs(filterData)

                // 小 tabs 的选中
                setSmallTabsValue(0) 
            // }
            
            setTabs([
                { title: <Badge overflowCount={99} text={counts1}>未回访</Badge>, value: '0' },
                { title: <Badge overflowCount={99} text={counts2}>已回访</Badge>, value: '1' },
            ])
           
            
        }

        
    }
    // 点击list 的时候跳转到详情
    const listClick = async (value) => {
        
        // const data = await http.post('/customer/checkCustomerBindoutUserId', {
        //     outUserId:value.client_id
        // });
        // console.log("获取外部联系人情况",data.data) 
        // if(data.isBind===1){ 
        //     history.push(`/user/details?isBind=${1}&outUserId=${value.client_id}&entryIsHome=${1} `, data.data[0]); //跳转到客户详情页面
        //     return 
        // } 
        history.push(`/user/details?isBind=${1}`,{
            customerCrmId: value.client_id
        })
    }

    const callPhone = async (item,value)=>{
        const data = await http.get('/feedback/wxworkMakeCall', {
            customerId:value.tb_customer_id,
            phoneUID:item.phoneUID
        });
        Toast.success(data.msg)
    }


    // 点击电话
    const clickPhone =async (e,value) =>{
        // http://wxwork.gzsg.cn/wxwork/feedback/wxworkMakeCall?userId=LiHao&hosId=1&managerId=1000920&
        // customerId=20211222104501953625
         e.stopPropagation();
        console.log("v1",value)
        // const data = await http.get('/feedback/wxworkMakeCall', {
        //     customerId:value.tb_customer_id
        // });
        // Toast.success(data.msg)
        let phoneList = await http.get('/feedback/wxworkPhoneList', {
            customerId:value.tb_customer_id
        });

        if(phoneList.code == 0){ 
            if(phoneList.data.length > 0){
                // setList(phoneList.data)
                // list=phoneList.data
                setTimeout(()=>{
                    Modal.alert('客户列表', 
                    (<div>
                        {
                          phoneList.data.map( (item,index) =>(
                          <div style={{display:'flex',flexDirection:'row',justifyContent:'center'}}>
                               <span> 号码{index+1} : </span> 
                               <span style={{marginLeft:"12px"}}> {item.phone}</span>
                               <Button onClick={()=>{callPhone(item,value)}} style={{marginLeft:"12px",fontSize:"12px",backgroundColor:"green",height:"26px",paddingLeft:"8px",paddingRight:"8px",lineHeight:"26px"}} >立即拨号</Button>
                           </div>
                        )  )
                      }
                       </div>)
                    , [{ text: '确定' }]
                    )
                },300)
            }   
        }else{
            Toast.fail(phoneList.msg)
        } 
    }
    const tabsHTML = (
        smallTabsData.map((elem,idex) => (
            <div  
                className='userList-row g-flex g-x-between g-mt32' 
                style={{padding: '0.25rem 0.2rem',margin:'10px', backgroundColor: '#FFFFFF'}}
                onClick={() => listClick(elem)}
            >
                <div className=' g-flex' >
                    <img src={elem.sex=='1'?woman:man} style={{width:'1rem',height:'1rem'}} className='g-round' alt="UserImg"/>
                    <div className='g-ml20 g-f24 g-c-999'>
                        <p className='g-f30 g-c-333 '>
                            <span style={{fontSize:'0.32rem',fontWeight:'bold'}}>{elem.name}</span>
                        </p> 
                        <p className='g-mt24'>卡号：<span>{elem.card_no}</span></p>
                        <p className='g-mt12' style={{lineHeight:'0.4rem'}}>计划回访人：{elem.scout_man}</p>
                        <p className='g-mt12' style={{lineHeight:'0.4rem'}}>开发人：{elem.developer}</p>
                        
                    </div>
                </div>
                <div className='g-f24 right-box-style-btn'>
                        {/* <button>1111</button> */}
                        {/* style={{pointerEvents:'auto'}} */}
                        <span class="iconfont icon-dianhua"  onClick={(e) => clickPhone(e,elem)}></span>
                        <span class="iconfont icon-huifangxinke"  onClick={(e) => nextStep(e,elem)}></span>
                        
                </div>
            </div>
        ))
    )
     
    return (
        <div className="v-return-visit">
            <div className='body-background-div'></div>

            <List className='g-mb10 g-p5-10 g-bg-f g-bdrs12 appointmentRecord-list-search-box'>

                    <Flex>
                        <Flex.Item>
                            <DatePicker mode="date" value={myDate1} onChange={d => {

                                // myDate1 = d
                                setMyDate1(d)

                                localStorage.setItem("timeSearch", JSON.stringify([d,myDate2  ]))

                                let dateNum = new Date(d).getTime()
                                let date2Num = new Date(myDate2).getTime()
                                if (Number(dateNum) > Number(date2Num)) {
                                    myDate2=d
                                    localStorage.setItem("timeSearch", JSON.stringify([d,d  ]))
                                }
                            }}>
                                <List.Item arrow="horizontal"></List.Item>
                            </DatePicker>
                        </Flex.Item>
                        <Flex.Item>
                            <DatePicker mode="date" value={myDate2} minDate={myDate1} onChange={d => { 
                                //   myDate2=d
                                setMyDate2(d)
                                  localStorage.setItem("timeSearch", JSON.stringify([myDate1,d  ]))
                                }}>
                                <List.Item arrow="horizontal"></List.Item>
                            </DatePicker>
                        </Flex.Item>
                        <Flex.Item><Button type="primary" size="small" className="appointmentRecord-list-search" 
                        onClick={() => submitSearch()} style={tabsVal === '0' ? { backgroundColor: '#39f', border: '1px solid #39f' } : { backgroundColor: '#06bd8a', border: '1px solid #06bd8a' }}>查询</Button></Flex.Item>
                    </Flex>
    
                </List>
            
            {/* {
                history.location.state ? (
                    <List className='g-mb10 g-p5-10 g-bg-f g-bdrs12 appointmentRecord-list-search-box'>

                    <Flex>
                        <Flex.Item>
                            <DatePicker mode="date" value={myDate1} onChange={d => {

                                myDate1 = d

                                localStorage.setItem("timeSearch", JSON.stringify([d,myDate2  ]))

                                let dateNum = new Date(d).getTime()
                                let date2Num = new Date(myDate2).getTime()
                                if (Number(dateNum) > Number(date2Num)) {
                                    myDate2=d
                                    localStorage.setItem("timeSearch", JSON.stringify([d,d  ]))
                                }
                            }}>
                                <List.Item arrow="horizontal"></List.Item>
                            </DatePicker>
                        </Flex.Item>
                        <Flex.Item>
                            <DatePicker mode="date" value={myDate2} minDate={myDate1} onChange={d => { 
                                  myDate2=d
                                  localStorage.setItem("timeSearch", JSON.stringify([myDate1,d  ]))
                                }}>
                                <List.Item arrow="horizontal"></List.Item>
                            </DatePicker>
                        </Flex.Item>
                        <Flex.Item><Button type="primary" size="small" className="appointmentRecord-list-search" 
                        onClick={() => submitSearch()} style={tabsVal === '0' ? { backgroundColor: '#39f', border: '1px solid #39f' } : { backgroundColor: '#06bd8a', border: '1px solid #06bd8a' }}>查询</Button></Flex.Item>
                    </Flex>
    
                </List>
                ):(
                    <List className='g-mb10 g-p5-10 g-bg-f g-bdrs12 appointmentRecord-list-search-box'>

                <Flex>
                    <Flex.Item>
                        <DatePicker mode="date" value={date} onChange={d => {
                            setDate(d)
                            let dateNum = new Date(d).getTime()
                            let date2Num = new Date(date2).getTime()
                            if (Number(dateNum) > Number(date2Num)) {
                                setDate2(d)
                            }
                        }}>
                            <List.Item arrow="horizontal"></List.Item>
                        </DatePicker>
                    </Flex.Item>
                    <Flex.Item>
                        <DatePicker mode="date" value={date2} minDate={date} onChange={d => { 
                            setDate2(d) 
                            }}>
                            <List.Item arrow="horizontal"></List.Item>
                        </DatePicker>
                    </Flex.Item>
                    <Flex.Item><Button type="primary" size="small" className="appointmentRecord-list-search" 
                    onClick={() => submitSearch()} style={tabsVal === '0' ? { backgroundColor: '#39f', border: '1px solid #39f' } : { backgroundColor: '#06bd8a', border: '1px solid #06bd8a' }}>查询</Button></Flex.Item>
                </Flex>

            </List>
 

                )
            } */}


          
            <div style={{ paddingTop: '53px' }} className={tabsVal === '0' ? 'tabs-style-1' : 'tabs-style-2'}>
                <Tabs tabs={tabs}
                    initialPage={0}
                    swipeable={false} 
                    onChange={(tab, index) => { console.log('onChange', index, tab); bigTabsChange(tab.value,index) }}
                    onTabClick={(tab, index) => { console.log('onTabClick', index, tab); }}
                >

                    {tabsVal === '0' && (
                        <div className="small-box">
                            <Tabs
                                tabBarBackgroundColor={tabsVal === '0' ? '#39f' : '#06bd8a'}
                                tabBarActiveTextColor="#fff"
                                tabBarInactiveTextColor="#fff"
                                tabs={smalltabs}
                                swipeable={false} 
                                page={smallTabsValue}
                                renderTabBar={props => <Tabs.DefaultTabBar {...props} page={3} />} onChange={(v,index) => tabsClick(v,index)}
                            >   
                                <div className="edit-card-box2">
                                    {smallTabsData.length > 0 ? (
                                        tabsHTML
                                    ):<div className='test-color'>暂无更多数据</div>}
                                 </div>
                            </Tabs>
                            {smalltabs.length < 1 && (<div className='test-color'>暂无更多数据</div>)}
                        </div>
                    )}
                        
                        
                    

                    {tabsVal === '1' && (
                        <div className="small-box">
                            <Tabs
                                tabBarBackgroundColor={tabsVal === '0' ? '#39f' : '#06bd8a'}
                                tabBarActiveTextColor="#fff"
                                tabBarInactiveTextColor="#fff"
                                tabs={smalltabs}
                                page={smallTabsValue}
                                swipeable={false}
                                renderTabBar={props => <Tabs.DefaultTabBar {...props} page={3} />} onChange={(v,index) => tabsClick(v,index)}
                            >
                                <div> 
                                    <div className="edit-card-box">
                                        {smallTabsData.length > 0 ? smallTabsData.map((item, idx) => (

                                            <Card className="card-edit-list" style={{ position: 'relative' }}>
                                                <Card.Body>
                                                    <div className="card-edit-flex-box">
                                                        <p>顾客姓名：</p><span>{item.name}</span>
                                                        <div className="clear"></div>
                                                    </div>
                                                    <div className="card-edit-flex-box">
                                                        <p>顾客卡号：</p><span>{item.card_no}</span>
                                                        <div className="clear"></div>
                                                    </div>
                                                    <div className="card-edit-flex-box">
                                                        <p>回访时间：</p><span>{item.actual_scout_date}</span>
                                                        <div className="clear"></div>
                                                    </div>
                                                    <div className="card-edit-flex-box">
                                                        <p>回访方式：</p><span>{item.scout_mode_name}</span>
                                                        <div className="clear"></div>
                                                    </div>
                                                    <div className="card-edit-flex-box">
                                                        <p>回访来源：</p><span>{item.task_source_name}</span>
                                                        <div className="clear"></div>
                                                    </div>
                                                    <div className="card-edit-flex-box">
                                                        <p>沟通状态：</p><span>{item.reveive_state_name}</span>
                                                        <div className="clear"></div>
                                                    </div>
                                                    <div className="card-edit-flex-box">
                                                        <p>回访目的：</p><span>{item.scout_purpose}</span>
                                                        <div className="clear"></div>
                                                    </div>
                                                    <div className="card-edit-flex-box">
                                                        <p>回访内容：</p><span>{item.scout_content}</span>
                                                        <div className="clear"></div>
                                                    </div>
                                                    <div className="card-edit-flex-box">
                                                        <p>回访员工：</p><span>{item.developer}</span>
                                                        {/* <span style={item.scout_state == 1 ? { color: '#2E8B57' } : (item.scout_state == 0 ? { color: '#FF4500' } : { color: '#808080' })} className="scount-name-color">{item.scout_state_name}</span> */}
                                                        <span className="scount-name-color"><img src={status1} /></span>
                                                        <div className="clear"></div>
                                                    </div>


                                                </Card.Body>

                                            </Card>))

                                            : <div className='test-color'>暂无更多数据</div>}
                                    </div>  
                                </div>

                            </Tabs>
                            {smalltabs.length < 1 && (<div className='test-color'>暂无更多数据</div>)}
                        </div>
                    )}
                    
                    

                </Tabs>
            </div>


            {/* <Button className={isiOSBool ? 'frequency-next-step2' : 'frequency-next-step'} type="warning" onClick={nextStep}>新增回访</Button> */}
           
            <Header />
        </div>
    )
}
export default ReturnVisit;